package task;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Creared with IntelliJ IDEA.
 * Description:线程池
 * User:yxd
 * Date:2022-03-30
 * Time:0:02
 */
class MyThreadPool{
    //描述任务 使用runnable
    //组织任务
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    //一个工作线程来获得线程
    static class Worker extends Thread{
        //方便得到阻塞队列实例
        private BlockingQueue<Runnable> queue = null;

        public Worker(BlockingQueue<Runnable> queue) {
            this.queue = queue;//得到实例
        }
        //执行实例

        @Override
        public void run() {
            while(true){
                try {
                    Runnable runnable = queue.take();//获得任务,没有就阻塞
                    //执行
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    //使用数组组织这些线程
    private List<Worker> workers = new ArrayList<>();
    public MyThreadPool(int n){
        Worker worker = new Worker(queue);
        worker.start();//启动
        workers.add(worker);
    }
    //使用submit方法,让程序员将任务放到线程池
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class Practice_5 {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 100; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello pool");
                }
            });
        }

    }
}
